package com.byxy.student.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.byxy.student.entity.UploadFile;
import com.byxy.student.service.UploadFileService;

@WebServlet("/servlet/file/upFile")
@MultipartConfig
public class StudentUploadServlet extends HttpServlet {

	private UploadFileService fileService;

	@Override
	public void init() throws ServletException {
		super.init();
		if (null == fileService) {
			ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
			fileService = (UploadFileService) ctx.getBean(UploadFileService.class);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 获取上传的文件
		Part part = req.getPart("file");
		// 获取上传文件的目录
		String root = req.getServletContext().getRealPath("/upload/");
		// 获取 上传文件名
		String fileName = part.getSubmittedFileName();//name.substring(name.indexOf("filename=\"") + 10, name.length() - 1);
		System.out.println(root + fileName);
		part.write(root + fileName);
		UploadFile sf = new UploadFile();
		sf.setName(fileName);
		sf.setPath(root+ fileName);
		fileService.addFile(sf);
		resp.sendRedirect("FileList");
	}
}
